package com.agent.vpsserver.common.utils.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 字符串工具类
 *
 * @author <a href="mailto:ludezh@dingtalk.com"> ludezh </a>
 * @version 1.0.0   2018/12/24,20:15
 * @since 1.0.0     2018/12/24,20:15
 */
@Component
@Slf4j
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        context = applicationContext;
    }

    public static void setContext(ApplicationContext applicationContext){
        if(context==null) {
            context = applicationContext;
        }
    }

    /**
     * 根据beanId获取配置在系统中的对象实例。
     *
     * @param beanId
     * @return Object
     * @exception
     * @since 1.0.0
     */
    public static Object getBean(String beanId) {
        try{
            return context.getBean(beanId);
        }
        catch(Exception ex){
            log.debug("getBean:" + beanId +"," + ex.getMessage());
        }
        return null;
    }

    /**
     * 获取Spring容器的Bean
     *
     * @param beanClass
     * @return T
     * @exception
     * @since 1.0.0
     */
    public static <T> T getBean(Class<T> beanClass) {
        try{
            return  context.getBean(beanClass);
        }
        catch(Exception ex){
            log.debug("getBean:" + beanClass +"," + ex.getMessage());
        }
        return null;
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> beanClass){
        return context.getBeansOfType(beanClass);
    }

    public static void cleanup(){
        context = null;
    }
}

